package com.bootdo.lvyou_specialty.service.impl;

import com.alibaba.fastjson.JSON;
import com.bootdo.common.redisUtils.JedisUtils;
import com.bootdo.common.utils.CurrencyUtils;
import com.bootdo.common.utils.SnowflakeIdWorker;
import com.bootdo.lvyou.domain.LvyouMember;
import com.bootdo.lvyou_specialty.dao.LvyouSpecialtyOrderContentDao;
import com.bootdo.lvyou_specialty.dao.LvyouSpecialtyOrderPartDao;
import com.bootdo.lvyou_specialty.dao.LvyouSpecialtyProductDao;
import com.bootdo.lvyou_specialty.domain.LvyouSpecialtyOrderContent;
import com.bootdo.lvyou_specialty.domain.LvyouSpecialtyProduct;
import com.bootdo.lvyou_specialty.domain.LvyouSpecialtyUserAddress;
import com.front.web.lvyou_specialty_front.pagevo.GoodsContentBodyVo;
import com.front.web.lvyou_specialty_front.pagevo.GoodsContentVo;
import com.front.web.lvyou_specialty_front.pagevo.GoodsOrderVo;
import com.front.web.lvyou_specialty_front.util.GoodsContentUtil;
import com.front.web.lvyou_specialty_front.util.OrderContentStatus;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import com.bootdo.lvyou_specialty.dao.LvyouSpecialtyOrderAllDao;
import com.bootdo.lvyou_specialty.domain.LvyouSpecialtyOrderAll;
import com.bootdo.lvyou_specialty.service.LvyouSpecialtyOrderAllService;
import org.springframework.transaction.annotation.Transactional;


@Service
public class LvyouSpecialtyOrderAllServiceImpl implements LvyouSpecialtyOrderAllService {
	@Autowired
	private LvyouSpecialtyOrderAllDao lvyouSpecialtyOrderAllDao;

	@Autowired
	private LvyouSpecialtyOrderPartDao lvyouSpecialtyOrderPartDao;

	@Autowired
	private LvyouSpecialtyOrderContentDao lvyouSpecialtyOrderContentDao;

	@Autowired
	private LvyouSpecialtyProductDao lvyouSpecialtyProductDao;
	
	@Override
	public LvyouSpecialtyOrderAll get(Long id){
		return lvyouSpecialtyOrderAllDao.get(id);
	}
	
	@Override
	public List<LvyouSpecialtyOrderAll> list(Map<String, Object> map){
		return lvyouSpecialtyOrderAllDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return lvyouSpecialtyOrderAllDao.count(map);
	}
	
	@Override
	public int save(LvyouSpecialtyOrderAll lvyouSpecialtyOrderAll){
	
		if(lvyouSpecialtyOrderAll.getId() != null) {
			return lvyouSpecialtyOrderAllDao.update(lvyouSpecialtyOrderAll);
		}else {
			return lvyouSpecialtyOrderAllDao.save(lvyouSpecialtyOrderAll);
		}		
	
		
	}
	
	@Override
	public int update(LvyouSpecialtyOrderAll lvyouSpecialtyOrderAll){
		return lvyouSpecialtyOrderAllDao.update(lvyouSpecialtyOrderAll);
	}
	
	@Override
	public int remove(Long id){
		return lvyouSpecialtyOrderAllDao.remove(id);
	}
	
	@Override
	public int batchRemove(Long[] ids){
		return lvyouSpecialtyOrderAllDao.batchRemove(ids);
	}

	@Override
	public LvyouSpecialtyOrderAll getByOrderNo(String orderNo) {
		return lvyouSpecialtyOrderAllDao.getByOrderNo(orderNo);
	}

	@Override
	public int wxBackGoodsNumber(LvyouSpecialtyOrderAll goodsOrder) {

		int result = 0;

		List<LvyouSpecialtyOrderContent> ordercontents = lvyouSpecialtyOrderContentDao.getByOrderNo(goodsOrder.getOrderNo());
		for (LvyouSpecialtyOrderContent content : ordercontents) {
			// 做销量的增加处理
			Long goodsId = content.getGoodsId();
			Integer goodsNumber = content.getGoodsNumber();
			LvyouSpecialtyProduct lvyouSpecialtyProduct = lvyouSpecialtyProductDao.get(goodsId);
			lvyouSpecialtyProduct.setSellNumber(lvyouSpecialtyProduct.getSellNumber() + goodsNumber);

			// 做库存的减少处理
			lvyouSpecialtyProduct.setReportory(lvyouSpecialtyProduct.getReportory() - goodsNumber);

			result = lvyouSpecialtyProductDao.update(lvyouSpecialtyProduct);

			// 通知商户

			if (result <= 0) {
				break;
			}
		}

		return result;
	}

	@Transactional
	@Override
	public GoodsOrderVo createOrder(Map<String, Object> redisMap,
									String[] goodsIds,
									LvyouMember lvyouMember,
									LvyouSpecialtyUserAddress lvyouSpecialtyUserAddress,
									boolean isMember,
									boolean toBuyAtOnce) throws NoSuchMethodError{

		Map<String, Object> toSettleMap = new HashMap<>();

		for (String one: goodsIds) {
			if (redisMap.containsKey(one)) {
				toSettleMap.put(one, redisMap.get(one));
				redisMap.remove(one);
			}
		}

		// 一个订单表
		LvyouSpecialtyOrderAll lvyouSpecialtyOrderAll = new LvyouSpecialtyOrderAll();

		// 设定收货地址
		lvyouSpecialtyOrderAll.setUserAddress(lvyouSpecialtyUserAddress.getReceiverAddress());
		lvyouSpecialtyOrderAll.setUserAddressId(lvyouSpecialtyUserAddress.getId());
		lvyouSpecialtyOrderAll.setUserOpenId(lvyouMember.getOpenid());

		// 设定订单编号
		String orderNo = SnowflakeIdWorker.getOrderNo("GOODSORDR");
		lvyouSpecialtyOrderAll.setOrderNo(orderNo);

		List<LvyouSpecialtyProduct> fromMap = lvyouSpecialtyProductDao.getFromMap(toSettleMap.keySet());
		List<GoodsContentVo> listContent = new ArrayList();
		List<GoodsContentBodyVo> bodyVoList = new ArrayList<>();
		GoodsContentUtil.createFromProduct(listContent, fromMap, toSettleMap);



		// 已经得到了content，进行遍历，并且进行存入数据库
		Double allMinuFee = 0D;
		Map<String, List<LvyouSpecialtyOrderContent>> merchantMap = new HashMap<>();
		List<LvyouSpecialtyOrderContent> contentSqlList = new ArrayList<>();
		for (GoodsContentVo one: listContent) {
			LvyouSpecialtyOrderContent contentNew = createContentNew(one, orderNo, lvyouSpecialtyUserAddress, isMember);
			contentNew.setUserOpenId(lvyouMember.getOpenid());
			allMinuFee += contentNew.getMinusFee();
			// lvyouSpecialtyOrderContentDao.save(contentNew);
			contentSqlList.add(contentNew);
		}

		Map<String, Object> bodyMap = GoodsContentUtil.createContentBodyList(bodyVoList, listContent, isMember);

		// 该for循环是用来进行计算运费的
		for (LvyouSpecialtyOrderContent one: contentSqlList) {

			for (GoodsContentBodyVo body : bodyVoList) {
				if (body.getMerchantId() == one.getMerchantId().longValue()) {
					if (body.isOne()) {
						String merchantOrderNo = SnowflakeIdWorker.getOrderNo("MERCHANTORDER");
						body.setMerchantOrderNo(merchantOrderNo);
//						one.setGoodsOrderNo(merchantOrderNo);
						one.setMerchantOrderNo(merchantOrderNo);
						one.setFreight(body.getFreight());
						body.setOne(false);
					} else {
						one.setMerchantOrderNo(body.getMerchantOrderNo());
						one.setFreight(0D);
					}
					one.setRealFee(CurrencyUtils.add(new BigDecimal(one.getGoodsFee()),new BigDecimal(one.getFreight())).doubleValue());
				}
			}
			one.setUserId(lvyouMember.getId());
			one.setUserMemberMobile(lvyouMember.getMobile());
			one.setUserMemberName(lvyouMember.getNickname());
			lvyouSpecialtyOrderContentDao.save(one);
		}

		// 该循环是为了产生多个orderAll对象，并且将content数据更新到数据库表中
//		int save = 0;
//
//		List<GoodsOrderVo> goodsOrderVos = new ArrayList<>();
//
//		for (GoodsContentBodyVo one: bodyVoList) {
//
//			GoodsOrderVo goodsOrderVo = new GoodsOrderVo();
//
//			LvyouSpecialtyOrderAll lvyouSpecialtyOrderAllNew = new LvyouSpecialtyOrderAll();
//			lvyouSpecialtyOrderAllNew.setStatus(1);
//			lvyouSpecialtyOrderAllNew.setOrderNo(one.getMerchantOrderNo());
//			lvyouSpecialtyOrderAllNew.setUserOpenId(lvyouMember.getOpenid());
//			lvyouSpecialtyOrderAllNew.setUserName(lvyouMember.getNickname());
//			lvyouSpecialtyOrderAllNew.setUserMobile(lvyouMember.getMobile());
//			lvyouSpecialtyOrderAllNew.setUserState(1);
//			lvyouSpecialtyOrderAllNew.setUserId(lvyouMember.getId());
//			lvyouSpecialtyOrderAllNew.setUserAddressId(lvyouSpecialtyUserAddress.getId());
//			lvyouSpecialtyOrderAllNew.setUserAddress(lvyouSpecialtyUserAddress.getReceiverAddress());
//			lvyouSpecialtyOrderAllNew.setMinusFee(one.getMinusFee());
//			lvyouSpecialtyOrderAllNew.setMoney(one.getOneMerchantFee());
//
//			save = lvyouSpecialtyOrderAllDao.save(lvyouSpecialtyOrderAllNew);
//			goodsOrderVo.setLvyouSpecialtyOrderAll(lvyouSpecialtyOrderAllNew);
//			goodsOrderVos.add(goodsOrderVo);
//		}

		// 用户信息、状态、运费
		lvyouSpecialtyOrderAll.setStatus(OrderContentStatus.WZF.getStatus());
		lvyouSpecialtyOrderAll.setUserId(lvyouMember.getId());
		lvyouSpecialtyOrderAll.setUserName(lvyouMember.getNickname());

		lvyouSpecialtyOrderAll.setCreateTime(new Date());
		lvyouSpecialtyOrderAll.setMinusFee(allMinuFee);
		if (isMember) {
			lvyouSpecialtyOrderAll.setUserState(2);
		} else {
			lvyouSpecialtyOrderAll.setUserState(1);
		}
		lvyouSpecialtyOrderAll.setMoney((Double) bodyMap.get("totalFee"));

		lvyouSpecialtyOrderAll.setUserMobile(lvyouMember.getMobile());

		// 更新订单对象
		 int save = lvyouSpecialtyOrderAllDao.save(lvyouSpecialtyOrderAll);

		// 创建订单

		List<GoodsContentBodyVo> goodsContentBodyVoList = new ArrayList<>();

		// 一个订单表现对象
		GoodsOrderVo goodsOrderVo = new GoodsOrderVo();

		GoodsContentUtil.createContentBodyList(goodsContentBodyVoList, listContent, isMember);
		goodsOrderVo.setList(goodsContentBodyVoList);
		goodsOrderVo.setLvyouSpecialtyOrderAll(lvyouSpecialtyOrderAll);

		if (save > 0) {

			for (LvyouSpecialtyOrderContent content : contentSqlList) {
				// 做销量的增加处理
				Long goodsId = content.getGoodsId();
				Integer goodsNumber = content.getGoodsNumber();
				LvyouSpecialtyProduct lvyouSpecialtyProduct = lvyouSpecialtyProductDao.get(goodsId);
				lvyouSpecialtyProduct.setSellNumber(lvyouSpecialtyProduct.getSellNumber() + goodsNumber);

				// 做库存的减少处理
				lvyouSpecialtyProduct.setReportory(lvyouSpecialtyProduct.getReportory() - goodsNumber);
				if (lvyouSpecialtyProduct.getReportory() < 0) {
					throw new NoSuchMethodError();
				}

				int result = lvyouSpecialtyProductDao.update(lvyouSpecialtyProduct);

				// 通知商户

				if (result <= 0) {
					throw new NoSuchMethodError();
				}
			}

			if (!toBuyAtOnce) {

				String memberCartKey = DigestUtils.sha256Hex(lvyouMember.getMobile() + "qylyshop");
				if (redisMap == null || redisMap.isEmpty()) {
					JedisUtils.del(memberCartKey);
				} else {
					JedisUtils.setObjectMap(memberCartKey, redisMap, 0);
				}
			}
			return goodsOrderVo;

		}

		return null;
	}

	@Transactional
	@Override
	public int cancelOrder(LvyouSpecialtyOrderAll orderAll, String merchantOrder) {

		lvyouSpecialtyOrderAllDao.update(orderAll);
		return lvyouSpecialtyOrderContentDao.changeStatus(merchantOrder, OrderContentStatus.YGQ.getStatus());
	}

	@Transactional
	@Override
	public int wxBackSstatus(LvyouSpecialtyOrderAll goodsOrder) {

		int result = 0;

		// 更新订单
		lvyouSpecialtyOrderAllDao.update(goodsOrder);

		// 更新分单表
		result = lvyouSpecialtyOrderContentDao.updateStatus(goodsOrder.getOrderNo(), goodsOrder.getWxOrderNo());
		List<LvyouSpecialtyOrderContent> contentList = lvyouSpecialtyOrderContentDao.getByOrderNo(goodsOrder.getOrderNo());

		changNumber(contentList, false);

		return result;
	}

	// 延时回调，设置为库存增加
	@Transactional
	@Override
	public int defferBack(LvyouSpecialtyOrderAll orderAll) {

		lvyouSpecialtyOrderAllDao.update(orderAll);
		List<LvyouSpecialtyOrderContent> contentSqlList = lvyouSpecialtyOrderContentDao.getByOrderNo(orderAll.getOrderNo());

		List<LvyouSpecialtyOrderContent> removeList = new ArrayList<>();
		for (LvyouSpecialtyOrderContent one: contentSqlList) {
			if (one.getStatus() == OrderContentStatus.TF.getStatus().intValue() || one.getStatus() == OrderContentStatus.YTK.getStatus().intValue() || one.getStatus() == OrderContentStatus.YGQ.getStatus().intValue()) {
				removeList.add(one);
			}
		}

		contentSqlList.removeAll(removeList);
		return changNumber(contentSqlList, true);
	}

	@Transactional
	@Override
	public int createTuikuanOrder(String merchantOrder) {
		int tuikuan = lvyouSpecialtyOrderContentDao.createTuikuan(merchantOrder, OrderContentStatus.TF.getStatus());
		return tuikuan;
	}

	// 这里的addflag是指库存的加减
	private int changNumber(List<LvyouSpecialtyOrderContent> contentSqlList, boolean addFlag) {
		int result = 0;
		for (LvyouSpecialtyOrderContent content : contentSqlList) {
			// 做销量的减少处理
			Long goodsId = content.getGoodsId();
			Integer goodsNumber = content.getGoodsNumber();
			LvyouSpecialtyProduct lvyouSpecialtyProduct = lvyouSpecialtyProductDao.get(goodsId);
			if (addFlag) {
				lvyouSpecialtyProduct.setSellNumber(lvyouSpecialtyProduct.getSellNumber() - goodsNumber);
			} else {
				lvyouSpecialtyProduct.setSellNumber(lvyouSpecialtyProduct.getSellNumber() + goodsNumber);
			}


			// 做库存的增加处理
			if (addFlag) {
				lvyouSpecialtyProduct.setReportory(lvyouSpecialtyProduct.getReportory() + goodsNumber);
			} else {
				lvyouSpecialtyProduct.setReportory(lvyouSpecialtyProduct.getReportory() - goodsNumber);
			}

			if (lvyouSpecialtyProduct.getReportory() < 0) {
				throw new NoSuchMethodError();
			}

			result = lvyouSpecialtyProductDao.update(lvyouSpecialtyProduct);

			if (result <= 0) {
				throw new NoSuchMethodError();
			}
		}
		return result;
	}

	private LvyouSpecialtyOrderContent createContentNew(GoodsContentVo goodsContentVo, String orderNo, LvyouSpecialtyUserAddress lvyouSpecialtyUserAddress, boolean isMember) {

		LvyouSpecialtyOrderContent lvyouSpecialtyOrderContent = new LvyouSpecialtyOrderContent();
		lvyouSpecialtyOrderContent.setGoodsId(goodsContentVo.getGoodsId());
		lvyouSpecialtyOrderContent.setGoodsPrice(goodsContentVo.getGoodsPrice());
		lvyouSpecialtyOrderContent.setGoodsHprice(goodsContentVo.getGoodsHprice());
		lvyouSpecialtyOrderContent.setGoodsName(goodsContentVo.getGoodsName());
		lvyouSpecialtyOrderContent.setGoodsNumber(goodsContentVo.getGoodsNumber());
		lvyouSpecialtyOrderContent.setGoodsOrderNo(orderNo);
		lvyouSpecialtyOrderContent.setMerchantId(goodsContentVo.getMerchantId());
		lvyouSpecialtyOrderContent.setGoodsStandard(goodsContentVo.getGoodsStandard());
		lvyouSpecialtyOrderContent.setMerchantName(goodsContentVo.getMerchantName());
		// lvyouSpecialtyOrderContent.setMerchantOrderNo(SnowflakeIdWorker.getOrderNo("MERCHANTORDER"));
		lvyouSpecialtyOrderContent.setFreight(goodsContentVo.getFreight());
		lvyouSpecialtyOrderContent.setUserAddressId(lvyouSpecialtyUserAddress.getId());

		// 进行地址的拼接
//		List<String> list = JSON.parseObject(lvyouSpecialtyUserAddress.getReceiverCitys(), List.class);
//		StringBuilder userAddressName = new StringBuilder();
//		for (String one: list) {
//			userAddressName.append(one);
//			userAddressName.append(" ");
//		}
		// String userAddressName = lvyouSpecialtyUserAddress.getReceiverCitys().replace(",", " ") + lvyouSpecialtyUserAddress.getReceiverName();
		lvyouSpecialtyOrderContent.setUserAddressName(lvyouSpecialtyUserAddress.getReceiverAddress());
		lvyouSpecialtyOrderContent.setUserMobile(lvyouSpecialtyUserAddress.getReceiverMobile());
		lvyouSpecialtyOrderContent.setUserUname(lvyouSpecialtyUserAddress.getReceiverName());
		lvyouSpecialtyOrderContent.setReceiverCitys(lvyouSpecialtyUserAddress.getReceiverCitys());

		lvyouSpecialtyOrderContent.setGoodsImages(goodsContentVo.getGoodsImage());
		lvyouSpecialtyOrderContent.setGoodsFee(CurrencyUtils.multiply(new BigDecimal(goodsContentVo.getGoodsNumber()), new BigDecimal(goodsContentVo.getGoodsPrice())).doubleValue());

		if (isMember) {
			lvyouSpecialtyOrderContent.setRealFee(CurrencyUtils.multiply(new BigDecimal(goodsContentVo.getGoodsNumber()), new BigDecimal(goodsContentVo.getGoodsHprice())).doubleValue());
		} else {
			lvyouSpecialtyOrderContent.setRealFee(CurrencyUtils.multiply(new BigDecimal(goodsContentVo.getGoodsNumber()), new BigDecimal(goodsContentVo.getGoodsPrice())).doubleValue());

		}
		lvyouSpecialtyOrderContent.setMinusFee(CurrencyUtils.minus(new BigDecimal(lvyouSpecialtyOrderContent.getGoodsFee()), new BigDecimal(lvyouSpecialtyOrderContent.getRealFee())).doubleValue());

		lvyouSpecialtyOrderContent.setStatus(OrderContentStatus.WZF.getStatus());


		return lvyouSpecialtyOrderContent;
	}
}
